<template>
    <van-nav-bar :title="`${$route.name === 'add_category' ? '新增' : '编辑'}分类`" left-text="返回" left-arrow @click-left="$router.back()"></van-nav-bar>
    <div class="category-form">
        <van-form @submit="submitForm">
            <van-cell-group inset>
                <van-field v-model="formData.name" name="name" label="名称" placeholder="请输入分类名称"
                    :rules="[{ required: true, message: '请输入分类名称' }]" />

                <van-field name="coverPic" label="封面" :rules="[{ required: true, message: '请上传分类图片' }]">
                    <template #input>
                        <kUpload modalCode="MA001" :busi-key="formData.coverPic"></kUpload>
                    </template>
                </van-field>
            </van-cell-group>

            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit">
                    保存
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { showToast } from 'vant';
import { useRouter, useRoute } from 'vue-router';
import { http } from '../../utils/request';
import kUpload from '../../components/kUpload.vue';
import { getSnowflakeId } from '../../api/systemController'

const router = useRouter();
const route = useRoute();

const formData = reactive({
    name: '',
    coverPic: ''
});

const fileList = ref([]);

// 上传前校验
const beforeRead = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
        showToast('只能上传图片文件!');
        return false;
    }
    if (!isLt2M) {
        showToast('图片大小不能超过 2MB!');
        return false;
    }
    return true;
};

// 读取文件后的处理
const afterRead = (file) => {
    // 此处模拟上传图片
    const formData = new FormData();
    formData.append('file', file.file);

    // 这里应该调用实际的上传API
    console.log('上传文件:', file);

    // 模拟上传
    setTimeout(() => {
        // 假设服务器返回图片地址
        formData.image = URL.createObjectURL(file.file);
        showToast('上传成功');
    }, 1000);
};

const submitForm = () => {
    // 这里调用保存接口
    console.log('提交的数据:', formData);
    if(route.name === 'add_category') {
        const postData = Object.assign({
            level: 0,
        }, formData);
        http.post('/category/saveOrUpdate', postData).then(res => {
            showToast('新增成功')
            router.back();
        })
    } else {
        const postData = Object.assign({
            id: route.query.id,
        }, formData);
        http.post('/category/saveOrUpdate', postData).then(res => {
            showToast('更新成功')
            router.back();
        })
    }
};

// 初始化数据
const getInfo = async () => {
    if(route.name === 'update_category') {
        http.get(`/category/getOne?id=${route.query.id}`).then(res => {
            formData.name = res.name;
            formData.coverPic = res.coverPic;
        })
    } else {
        formData.coverPic = await getSnowflakeId()
    }
}

onMounted(() => {
    getInfo()
})

const cancel = () => {
    router.back();
};
</script>

<style scoped>
.category-form {
    padding: 16px 0;
}
</style>